import java.io.*;
import java.net.*;

public class SimpleEchoServer {
    protected static int DEFAULT_PORT = 12345;
    protected int port;
    protected ServerSocket server;

    public SimpleEchoServer() throws InvalidPortNumberException {
        this(DEFAULT_PORT);
    }

    public SimpleEchoServer(int port) throws InvalidPortNumberException {
        validatePort(port);
        this.port = port;
    }

    public boolean isRunning(){
        return (this.server == null ) ? false : !this.server.isClosed();
    }

    public int getPort(){
        return this.port;
    }

    public void setPort(int port) throws InvalidPortNumberException {
        validatePort(port);
        this.port = port;
    }

    public void start() throws IOException {
        Socket socket;
        PrintWriter out;
        BufferedReader in;
        String message;

        this.server = new ServerSocket(port);
        socket = this.server.accept();
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        message = in.readLine();
        out.println(message);

        socket.close();
    }

    public void stop() throws IOException {
        this.server.close();
    }

    private void validatePort(int port) throws InvalidPortNumberException {
        if ( port < 0 || port > 65535) {
            throw new InvalidPortNumberException();
        }
    }
}
